package com.cdream.basic.java8;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.cdream.basic.java8.model.OrderDO;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.math.BigDecimal.*;

/**
 * @author cdream
 * @date 2020-06-14
 */
public class StreamExample {
        public static final String COMPLETE = "complete";
        private static final String NOT_COMPLETE = "not_complete";
        private static List<OrderDO> orderList = CollUtil.newArrayList(
            OrderDO.builder().id(1).state(COMPLETE).createTime(DateUtil.parse("20200101")).totalAccount(ONE).build(),
            OrderDO.builder().id(2).state(NOT_COMPLETE).createTime(DateUtil.parse("20200201")).totalAccount(TEN).build(),
            OrderDO.builder().id(3).state(NOT_COMPLETE).createTime(DateUtil.parse("20200103")).totalAccount(ZERO).build(),
            OrderDO.builder().id(4).state(NOT_COMPLETE).createTime(DateUtil.parse("20200401")).totalAccount(TEN).build(),
            OrderDO.builder().id(5).state(COMPLETE).createTime(DateUtil.parse("20200501")).totalAccount(ONE).build()
    );


        public static void main(String[] args) {
            // 1.获取未完成订单，并按照创建时间先后排序,再获取其中的前两个
            List<OrderDO> completeOrders = orderList.stream()
                    .filter(a -> NOT_COMPLETE.equals(a.getState()))
                    .sorted((o1, o2) -> DateUtil.compare(o1.getCreateTime(),o2.getCreateTime()))
                    .limit(2)
                    .collect(Collectors.toList());
            System.out.println(completeOrders);

            // 2. 按照状态进行分组
            Map<String, List<OrderDO>> groupByState = orderList.stream().collect(Collectors.groupingBy(a -> a.getState()));
            System.out.println(groupByState);

            // 3. 做一个转换成id-account的Map
            List<Map<Integer, BigDecimal>> idAccountMap = orderList.stream()
                    .map(a -> MapUtil.of(a.getId(), a.getTotalAccount()))
                    .collect(Collectors.toList());
            System.out.println(idAccountMap);


            // 4. 将所有id按"，"连接
            String commaId = orderList.stream().map(a -> String.valueOf(a.getId())).collect(Collectors.joining(",",
                    "start","end"));
            System.out.println(commaId);


            // 5.计算总金额
            BigDecimal totalAccount = orderList.stream().map(a -> a.getTotalAccount()).reduce(ZERO, (o1, o2) -> o1.add(o2));


            // 6. 转换成id->本身的map 可用于填充属性
            Map<Integer, OrderDO> idMap = orderList.stream().collect(Collectors.toMap(a -> a.getId(), a -> a, (v1, v2) -> v1));


            // 7. forEach简单操作
            orderList.stream().map(a->a.getState()).forEach(a-> System.out.println(a));



        }



}
